/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    //利用满二叉树的特性：2 ^ (深度) - 1
    //求以某个节点为根节点的子树，判断若为满二叉树，直接利用公式返回，
    //避免一些不必要的遍历
    //若不为满二叉树继续往下递归,直到叶子节点为止,最坏情况叶子节点就是一个满二叉树
    public int countNodes(TreeNode root) {
        return getCount(root);
    }

    public int getCount(TreeNode node){
        if(node == null) return 0;

        int leftDepth = 0, rightDepth = 0;
        TreeNode left = node.left;
        TreeNode right = node.right;
        while(left != null){
            left = left.left;
            leftDepth++;
        }
        while(right != null){
            right = right.right;
            rightDepth++;
        }

        //若为满二叉树,直接返回节点数量
        if(leftDepth == rightDepth) return (2 << leftDepth) - 1;
            //否则继续求子树情况
        else return getCount(node.left) + getCount(node.right) + 1;
    }
}